package com.bzxgc.sgwer.common.Interceptor;

import com.bzxgc.sgwer.common.util.JsonUtils;
import com.bzxgc.sgwer.entity.menu.Menu;
import com.bzxgc.sgwer.entity.role.Role;
import com.bzxgc.sgwer.entity.user.User;
import com.bzxgc.sgwer.service.menu.MenuService;
import com.bzxgc.sgwer.service.role.RoleService;
import com.bzxgc.sgwer.service.user.UserRoleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletContext;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.List;

@Slf4j
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        User user = (User) request.getSession().getAttribute("user");
//        if (user == null) {
//            response.sendRedirect("/login");
//            return false;
//        }

        // 获取Spring容器
        ServletContext context = request.getServletContext();
        ApplicationContext ac = WebApplicationContextUtils.getWebApplicationContext(context);

        // 获取角色
        RoleService roleService = ac.getBean("roleService", RoleService.class);
//        List<Role> roleList = roleService.getRoleByUserId(user.getId());
        List<Role> roleList = roleService.getRoleByUserId(1L);
        Role role = null;
        if (roleList.size() > 0) {
            for (Role r : roleList) {
                if ("true".equals(r.getMainRole())) {
                    role = r;
                    break;
                }
            }
        }
        if (role == null) {
            role = new Role();
            role.setName("无职位");
        }
        request.setAttribute("role", role);

        // 获取菜单
        MenuService menuService = ac.getBean("menuService", MenuService.class);
        List<Menu> menuList = menuService.getOneMenuByRoleIds(roleList);
        request.setAttribute("menuList", menuList);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
